<template>
  <div class="cart-box">
    <div class="btn" v-show="foodNum > 0" @click="decCart">
      <img v-if="disableDec" src="../../../static/imgs/dis_add.png" width="100%" height="100%">
      <img v-else src="../../../static/imgs/dec.png" width="100%" height="100%">
    </div>
    <div class="num" v-show="foodNum > 0">{{foodNum}}</div>
    <div class="btn" @click="addCart($event)">
      <img v-if="foodNum > 0" src="../../../static/imgs/add_active.png" width="100%" height="100%">
      <img v-else src="../../../static/imgs/add.png" width="100%" height="100%">
    </div>
  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex'

  export default {
    name: 'MenuControl',

    data() {
      return {}
    },

    props: {
      food: {
        type: Object
      }
    },

    components: {},

    mounted() {
      let lan = localStorage.getItem("lan");
      if(lan){
        this.$i18n.locale = lan
      }
      this.$nextTick(() => {
      })
    },

    watch: {},

    computed: {
      ...mapState([
        'cartFoods'
      ]),
      foodNum() {
        let foodNum = 0
        if (this.cartFoods) {
          this.cartFoods.filter(({ id }) => id === this.food.id).forEach(({ num })=> {
            foodNum += num
          })
          return foodNum
        } else {
          return this.food.num ? this.food.num : 0
        }
      },
      disableDec() {
        if (this.cartFoods) {
          let foodInCart = this.cartFoods.filter(({ id }) => id === this.food.id)
          return foodInCart.length > 1 ? true : false
        }else {
          return false
        }
      }
    },

    filters: {},

    methods: {
      ...mapMutations([
        'DEC_CART'
      ]),
      addCart(event) {
        this.$emit('add', JSON.parse(JSON.stringify(this.food)), event.target)
      },
      decCart() {
        this.$emit('dec', JSON.parse(JSON.stringify(this.food)), this.disableDec)
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "../../../static/css/mixin";

  .cart-box {
    @include fja();

    .btn {
      @include wh(1.2rem, .8rem)
    }
    .num {
      padding: 0 .36rem;
      @include fscfw(.4rem)
    }
  }
</style>
